package com.meibao.user.service;

import com.meibao.common.enums.ExceptionEnums;
import com.meibao.common.exception.MbException;
import com.meibao.common.utils.NumberUtils;
import com.meibao.user.mapper.UserMapper;
import com.meibao.user.pojo.User;
import com.meibao.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String KEY_PREFIX = "user:verify:phone:";
    public Boolean checkData(String data, Integer type) {
        User record = new User();
        //判断数据类型
        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new MbException(ExceptionEnums.INVALID_USER_DATA_TYPE);
        }
        return userMapper.selectCount(record) ==0;
    }

    public void sendCode(String phone) {
        String key = KEY_PREFIX + phone;
        //生成验证码
        String code = NumberUtils.generateCode(6);
        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend("mb.sms.exchange","sms.verify.code", msg);

        //保存验证码
        redisTemplate.opsForValue().set(key, code, 5 , TimeUnit.MINUTES);
    }

    public void register(User user, String code) {
        //校验验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if(!StringUtils.equalsIgnoreCase(code, cacheCode)){
            throw new MbException(ExceptionEnums.INVALID_VERITY_CODE);
        }
        //对密码加密
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        //写入数据库
        user.setCreated(new Date());
        userMapper.insert(user);
    }

    public User queryUserByUsernameAndPassword(String username, String password) {
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        if(user ==null){
            throw new MbException(ExceptionEnums.INVALID_USERNAME_PASSWORD);
        }
        //数据校验
        if(!StringUtils.equals(user.getPassword(), CodecUtils.md5Hex(password, user.getSalt()))){
            throw new MbException(ExceptionEnums.INVALID_USERNAME_PASSWORD);
        }
        //用户名和密码正确
        return user;
    }
}
